import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

interface User {
    id: number
    username: string
    email?: string
    avatar?: string
}

export const useUserStore = defineStore('user', () => {
    // 从localStorage初始化状态
    const currentUser = ref<User | null>(
        localStorage.getItem('currentUser')
            ? JSON.parse(localStorage.getItem('currentUser')!)
            : null
    )

    const token = ref(localStorage.getItem('token') || 'admin-demo-token')
    const isLoggedIn = computed(() => !!token.value)

    // 模拟登录 - 保持admin用户登录状态
    const login = async (username: string, password: string): Promise<void> => {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (username === 'admin' && password === '123456') {
                    const user = {
                        id: 1,
                        username: 'admin',
                        email: 'admin@easygo.com',
                        avatar: '/avatars/admin.png'
                    }

                    currentUser.value = user
                    token.value = 'admin-demo-token'

                    // 持久化到localStorage
                    localStorage.setItem('currentUser', JSON.stringify(user))
                    localStorage.setItem('token', token.value)

                    resolve()
                } else {
                    reject(new Error('用户名或密码错误'))
                }
            }, 500)
        })
    }

    const logout = (): void => {
        currentUser.value = null
        token.value = ''
        localStorage.removeItem('currentUser')
        localStorage.removeItem('token')
    }

    // 初始化时检查token
    const init = (): void => {
        if (!token.value) {
            token.value = 'admin-demo-token'
        }
        if (!currentUser.value) {
            currentUser.value = {
                id: 1,
                username: 'admin',
                email: 'admin@easygo.com',
                avatar: '/avatars/admin.png'
            }
        }
    }

    init()

    return {
        currentUser,
        token,
        isLoggedIn,
        login,
        logout
    }
})